import React, { Component } from 'react';
import { View } from 'react-native';
import { SearchBar, Words } from 'bee/components/Search';
import { request } from 'bee/utils/request';
import noop from 'bee/utils/noop';
import Toast from 'bee/components/Toast';

// @flow
type Props = {
  navigation: Object,
};

export default class Search extends Component<Props> {
  constructor() {
    super();

    this.state = {
      keyword: '',
      words: [],
    };

    this.getDataFromServer = this.getDataFromServer.bind(this);
    this.confirmSearch = this.confirmSearch.bind(this);
    this.labelOnPress = this.labelOnPress.bind(this);
    this.cancelSearch = this.cancelSearch.bind(this);
  }

  componentDidMount() {
    this.getDataFromServer();
  }

  getDataFromServer() {
    request('/keyword')
      .then(data => {
        this.setState({ words: data });
      })
      .catch(e => {
        console.error(e);
      });
  }

  confirmSearch() {
    this.props.navigation.navigate('Products', {
      keyword: this.state.keyword,
    });
  }

  labelOnPress(word) {
    this.props.navigation.navigate('Products', {
      keyword: word,
    });
  }

  cancelSearch() {
    this.props.navigation.goBack();
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        {/* 搜索框 */}
        <SearchBar
          value={this.state.keyword}
          confirm={this.confirmSearch}
          cancel={this.cancelSearch}
          onChangeText={keyword => {
            this.setState({ keyword });
          }}
        />
        {/* 搜索关键词 */}
        <Words words={this.state.words} onPress={this.labelOnPress} />
      </View>
    );
  }
}
